"""
Verify AIPPT Download Image API
Test the /api/v1/aippt/down endpoint for caching template cover images
"""
import sys
import os
from dotenv import load_dotenv
from pathlib import Path

# Load environment variables
load_dotenv()

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent))

# Verify configuration
if not os.getenv("AIPPT_TOKEN"):
    print("ERROR: AIPPT_TOKEN not found in environment variables")
    print("Please set AIPPT_TOKEN in .env file")
    sys.exit(1)

import requests
from src.llm.aippt_app.services.template_service import TemplateService


def test_download_api():
    """Test the download image API endpoint"""
    print("=" * 60)
    print("Testing AIPPT Download Image API")
    print("=" * 60)

    # Step 1: Get template list to get cover URLs
    print("\n[Step 1] Getting template list...")
    service = TemplateService()
    result = service.list_templates(current=1, size=3, template_type=1)

    if result.get('code') != 0:
        print(f"Failed to get templates: {result}")
        return False

    templates = result.get('data', [])
    if not templates:
        print("No templates found")
        return False

    print(f"Found {len(templates)} templates")

    # Test with first template
    template = templates[0]
    template_id = template.get('id')
    cover_url = template.get('coverUrl')

    print(f"\nTemplate ID: {template_id}")
    print(f"Cover URL: {cover_url}")

    # Step 2: Test first request (should download)
    print("\n[Step 2] First request - should download from remote...")
    api_url = f"http://localhost:9000/api/v1/aippt/down?url={cover_url}"

    response1 = requests.get(api_url)
    print(f"Status code: {response1.status_code}")
    print(f"Content-Type: {response1.headers.get('Content-Type')}")
    print(f"Content-Length: {len(response1.content)} bytes")

    if response1.status_code != 200:
        print(f"Failed: {response1.text}")
        return False

    # Save first response for comparison
    first_content = response1.content

    # Step 3: Test second request (should use cache)
    print("\n[Step 3] Second request - should use cached version...")
    response2 = requests.get(api_url)
    print(f"Status code: {response2.status_code}")
    print(f"Content-Type: {response2.headers.get('Content-Type')}")
    print(f"Content-Length: {len(response2.content)} bytes")

    if response2.status_code != 200:
        print(f"Failed: {response2.text}")
        return False

    # Verify both responses are identical
    second_content = response2.content
    print(f"\nContent identical: {first_content == second_content}")

    # Step 4: Test with multiple templates
    print("\n[Step 4] Testing with multiple templates...")
    for i, template in enumerate(templates[:3], 1):
        tid = template.get('id')
        curl = template.get('coverUrl')
        api_url = f"http://localhost:9000/api/v1/aippt/down?url={curl}"

        print(f"\nTemplate {i}: {tid}")
        response = requests.get(api_url)
        print(f"  Status: {response.status_code}")
        print(f"  Size: {len(response.content)} bytes")

        if response.status_code != 200:
            print(f"  Failed: {response.text}")
            return False

    print("\n" + "=" * 60)
    print("Download Image API Test PASSED")
    print("=" * 60)
    return True


if __name__ == "__main__":
    try:
        print("\nNOTE: This test requires the server to be running on localhost:9000")
        print("Please start the server with: python src/main.py")
        print("\nStarting test in 3 seconds...")

        import time
        time.sleep(3)

        success = test_download_api()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"\nTest failed with error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
